//
//  LocationManager.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/9/13.
//

import Foundation
import CoreLocation
import Combine
import MapKit
//import Logging

class LocationManager : NSObject,ObservableObject {
    static let shared = LocationManager()

    var locationManager = CLLocationManager()
    
    private override init() {
        super.init()

        self.locationManager.delegate  = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.distanceFilter = 10.0
        self.locationManager.startUpdatingLocation()
        requestLocation()

    }

    func requestLocation() {
        print(statusString)
        self.hasSetRegion = false
        locationManager.requestLocation()
    }

    private var hasSetRegion = false

    @Published var locationStatus : CLAuthorizationStatus?

    var lastLocation:CLLocation?


    var statusString : String {
       get {
          guard let status = locationStatus else {
             return "unknown"
          }

          switch status {
             case .notDetermined : return "notDeterminded"
             case .authorizedWhenInUse:
                return "authorizedWhenInUse"
             case .authorizedAlways :
                return "authorizedAlways"
             case .restricted:return "restricted"
             case .denied:return "denied"
             default:return "unknown"
          }
       }
       set {
          objectWillChange.send()
          print("GPS:\(newValue)")
       }
    }

}

extension LocationManager:CLLocationManagerDelegate {

   func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
      locationStatus = manager.authorizationStatus
      print("GPS: \(manager.authorizationStatus)")
   }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("完成定位 locationManager")
        if let location = locations.first {
            ViewModel.shared.lastLocation = location.coordinate
            CarOrder.shared.startPos = location.coordinate
            print("didUpdateLocations 拿到的定位： CarOrder.shared.startPos: latitude:\(location.coordinate.latitude)-longitude:\(location.coordinate.longitude)")
            ViewModel.shared.saveLastLocation()
            print("持续定位: latitude:\(location.coordinate.latitude)-longitude:\(location.coordinate.longitude)")
            DispatchQueue.main.async{
//                NotificationCenter.default.post(
//                    name:.location,
//                    object: nil,
//                    userInfo: ["location":location]
//                )
                
            }
            
           
//            if !self.hasSetRegion {
//                self.hasSetRegion = true
//            }
        }
    }

   func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
      switch status {
         case .authorizedAlways, .authorizedWhenInUse:
               // 定位权限开启
            logger.info("GPS: authorized")
            manager.startUpdatingLocation()
         case .denied:
            logger.info("GPS: denied")
               // 用户拒绝了此应用程序访问其位置的权限。
         case .restricted:
            logger.info("GPS: restricted")
               // 父母控制限制了此应用程序访问位置的权限。
         case .notDetermined:
               // 用户还没有选择是否允许此应用访问其位置。
            logger.info("GPS: notDetermined")
            manager.requestWhenInUseAuthorization()
         default:
            logger.info("GPS: default")
      }
   }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}
